package com.cmc6.server.service.impl;

import cn.hutool.system.RuntimeInfo;
import cn.hutool.system.SystemUtil;
import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import com.cmc6.server.model.vo.ServerInfoVO;
import com.cmc6.server.service.ServerService;
import org.springframework.stereotype.Service;
import oshi.hardware.GlobalMemory;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;

import java.util.List;

@Service
public class ServerServiceImpl implements ServerService {

    /**
     * 获取服务器运行情况
     */
    @Override
    public ServerInfoVO info() {

        // jvm信息
        RuntimeInfo runtimeInfo = SystemUtil.getRuntimeInfo();

        // 操作系统内存信息
        GlobalMemory memory = OshiUtil.getMemory();

        // cpu信息
        CpuInfo cpuInfo = OshiUtil.getCpuInfo();

        long sizeTotal = 0; // 磁盘总大小
        long freeTotal = 0; // 磁盘总可使用的大小

        OperatingSystem os = OshiUtil.getOs();
        FileSystem fileSystem = os.getFileSystem();
        List<OSFileStore> fileStores = fileSystem.getFileStores();
        for (OSFileStore item : fileStores) {
            sizeTotal += item.getTotalSpace();
            freeTotal += item.getUsableSpace();
        }

        // 本接口返回值
        ServerInfoVO resVO = new ServerInfoVO();
        resVO.setJvmMaxMemory(runtimeInfo.getTotalMemory());
        resVO.setJvmUsingMemory(runtimeInfo.getTotalMemory() - runtimeInfo.getFreeMemory());
        resVO.setMemoryTotal(memory.getTotal());
        resVO.setMemoryUsing(memory.getTotal() - memory.getAvailable());
        resVO.setCpuUsing(100 - cpuInfo.getFree());
        resVO.setSizeTotal(sizeTotal);
        resVO.setWritesTotal(sizeTotal - freeTotal);

        return resVO;
    }
}
